// 导入基础包
import React, { useState, useEffect } from 'react'
import { connect } from 'umi'

// 导入处理函数
import * as xl from '../../methods/xlsx'
import *as tags from '../../methods/tags'
// 导入UI组件
import { Tabs, Upload, Button, Table, Divider, Spin, Drawer, Modal } from 'antd'
import { FileExcelTwoTone } from '@ant-design/icons';
import css from './add_file.less'

const { TabPane } = Tabs

const PageView = (props) => {
    const { global: state, dispatch, loading } = props
    const [tabid, setTabid] = useState('1')
    console.log(state.repeat_list)
    console.log(state.table_cols)

    // 禁用默认事件
    useEffect(() => {
        document.addEventListener('drop', e => e.preventDefault(), false)
        document.addEventListener('dragover', e => e.preventDefault(), false)

        window.onresize = () => {
            dispatch({ type: 'global/save', payload: { root_height: document.body.offsetHeight } })
        }
    })

    // 上传组件参数
    const Dragger_props = {
        name: 'file',
        listType: 'picture',
        maxCount: 1,
        onChange: (e) => {
            xl.upload_onChange(e, state, dispatch)
            tags.rowSelection([], state, dispatch)
        },
        beforeUpload: file => {
            xl.open_file(file, dispatch)
        },
        onRemove: () => xl.remov_file(dispatch)
    }

    const openSheet = e => {
        xl.open_sheet(e, state, dispatch)
        tags.rowSelection([], state, dispatch)
    }

    const saveTags = e => {
        tags.save_tags(state, dispatch)
        tags.rowSelection([], state, dispatch)
        setTabid('3')
    }

    const saveList = () => {
        let upload_file = tags.format_data(state.srowkey, state, dispatch)
        tags.save_list_to_service(upload_file)
        dispatch({ type: 'global/save', payload: { loading: true } })
    }

    const drawer_close = () => {
        console.log('xxx')
        Modal.confirm({
            title: '是否放弃处理？',
            content: '点击确认将不做任何处理!',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                dispatch({ type: 'global/save', payload: { repeat_view: false, srowkey: [],loading:false } })
            }
        });
    }

    const exp_xlsx = () => {
        var repeat_data = xl.format_repeat(state, dispatch)
        xl.export_xlsx(repeat_data, `${state.upload_file.substring(0, state.upload_file.lastIndexOf("."))}[${state.sheet}](重复的).xlsx`)
    }

    const Tag = props => {
        const { tag } = props
        const tag_methods = {
            onDragStart: e => {
                e.dataTransfer.setData("Text", e.target.id)
            },
            onDrag: e => {
                e.target.className = css.tag_drag
            },
            onDragEnd: e => {
                e.target.className = css.tag
            }
        }

        return (
            <div id={tag} className={css.tag} draggable {...tag_methods}>{tag}</div>
        )
    }

    const if_tag = () => {
        if (state.tag_bind.xm.length !== 0 && state.tag_bind.sfz.length !== 0 && state.tag_bind.dh.length !== 0) {
            return false
        } else {
            return true
        }
    }

    const TableDrop = props => {
        const { tag, dispatch, state } = props

        const tag_methods = {
            onDrop: e => {
                tags.setClassName(e.target, 'table_drop_box', css.table_drop_box)
                tags.drop(e, tag.multi, dispatch, state)
            },
            onDragOver: e => {
                tags.setClassName(e.target, 'table_drop_box', css.table_drop_box_over)
            },
            onDragLeave: e => {
                tags.setClassName(e.target, 'table_drop_box', css.table_drop_box)
            }
        }

        return (
            <div className={css.table_tag}>
                <p>{tag.title} <span>{state.tag_bind[tag.key].length}/{tag.multi}</span></p>
                <div id={tag.key} className={css.table_drop_box} {...tag_methods}>
                    {state.tag_bind[tag.key].map((t, tid) =>
                        <Tag key={tid} tag={t} />
                    )}
                </div>
            </div>
        )
    }

    const rowSelection = {
        selectedRowKeys: state.srowkey,
        fixed: true,
        onChange: keys => {
            tags.rowSelection(keys, state, dispatch)
        },
    };

    return (
        <div>
            <Spin spinning={state.loading}>
                <Tabs activeKey={tabid} onTabClick={e => {
                    setTabid(e)
                    if (e === '3') saveTags()
                }}>
                    <TabPane tab="(1).导入文件" key="1">
                        <div>
                            <div className={css.btn}>
                                <Button disabled={state.file_data.length === 0 ? true : false} type="primary" onClick={() => setTabid('2')}>确定导入数据，进入下一步</Button>
                            </div>
                            <Upload.Dragger {...Dragger_props}>
                                <p className="ant-upload-drag-icon">
                                    <FileExcelTwoTone />
                                </p>
                                <p className="ant-upload-text">点击选取文件或拖入文件</p>
                                <p className="ant-upload-hint">
                                    请预先处理好表格文件，请确保表头在文件的第一行，而且是单行表头，一行一条数据，并删除多余数据信息！
                        </p>
                            </Upload.Dragger>
                        </div>
                        <div className={css.sheets}>
                            <Button type="text">选择要导入的工作表</Button>
                            {state.sheet_names.map((n, id) =>
                                <Button key={id} onClick={() => openSheet(n)}
                                    type={state.sheet === n ? 'primary' : 'default'}
                                >{n}</Button>
                            )}
                        </div>
                        <div>
                            <Table size="small" bordered
                                columns={state.file_cols}
                                dataSource={state.file_data}
                                scroll={{ x: 2500, y: state.root_height - 480, scrollToFirstRowOnChange: true }}
                                pagination={false}
                            />
                        </div>
                    </TabPane>
                    <TabPane disabled={state.file_data.length === 0 ? true : false} tab="(2).设置文件表头与系统关联" key="2">
                        <div className={css.btn}>
                            <Button onClick={() => tags.reset_tags(state, dispatch)}>重置</Button>
                            <Divider type="vertical" />
                            <Button disabled={if_tag()} type="primary" onClick={saveTags}>保存表头标签，进入下一步</Button>
                        </div>
                        <div id={css.file_tags} className={css.file_tags} onDrop={e => tags.drop(e, 100, dispatch, state)}>
                            {state.file_data_cols.map((tag, tid) =>
                                <Tag key={tid} tag={tag} />
                            )}
                        </div>
                        <h3 style={{ textAlign: 'center', fontWeight: 100 }}>*请拖动上面的文件表头标签到下面对应的标签内，姓名、身份证、电话号码为必填项*</h3>
                        <div className={css.table_tags}>
                            {state.table_cols.map((tag, tid) =>
                                <TableDrop key={tid} tag={tag} dispatch={dispatch} state={state} />
                            )}
                        </div>
                    </TabPane>
                    <TabPane disabled={if_tag()} tab="(3).检查关联的数据是否正确" key="3">
                        <div className={css.btn}>
                            共选中：{state.srowkey.length} 条数据
                            <Divider type="vertical" />
                            <Button disabled={state.srowkey.length === 0 ? true : false} type="primary" onClick={saveList}>确定将选中的数据添加到数据库</Button>
                        </div>
                        <Table size="small" bordered
                            columns={state.table_cols}
                            dataSource={state.format_file_data}
                            scroll={{ x: 2500, y: state.root_height - 180, scrollToFirstRowOnChange: true }}
                            pagination={false}
                            rowSelection={rowSelection}
                        />
                    </TabPane>
                </Tabs>
            </Spin>
            <Drawer
                title={`共有：${state.repeat_list.length} 条重复数据需要处理`}
                placement="bottom"
                height="100vh"
                closable
                onClose={drawer_close}
                visible={state.repeat_view}
            >
                <div>
                    已选择：{state.srowkey.length}条数据
                            <Divider type="vertical" />
                    <Button disabled={state.srowkey.length === 0 ? true : false} onClick={exp_xlsx}>导出表格文件</Button>
                    <Divider type="vertical" />
                    <Button disabled={state.srowkey.length === 0 ? true : false}
                        onClick={() => {
                            console.log('print')
                        }}
                    >打印表格</Button>
                    <Divider type="vertical" />
                    <Button disabled>合并数据</Button>

                </div>

                <Table size="small" bordered
                    id="repeat_list"
                    columns={state.table_cols}
                    dataSource={state.repeat_list}
                    scroll={{ x: 2500, y: 700, scrollToFirstRowOnChange: true }}
                    pagination={false}
                    rowSelection={rowSelection}
                />
            </Drawer>
        </div>
    )
}

export default connect(({ global, loading }) => ({ global, loading }))(PageView)